<?php
#####################################
# * @Author: lehieu008              #
# * @Email: lehieu008@gmail.com     #
# * @Copyright: 2008 - 2010         #
#####################################
if(!defined('BASEPATH'))exit('No direct script access allowed');
function is_logined($id = 0, $group = 0, $type = 'ADMIN')
{
    switch(trim(strtoupper($type)))
    {
        case 'ADMIN':
            if($id && (int)$id > 0 && $group && (int)$group >= 4)
            {
                return true;
            }
            break;
        case 'HOME':
            if($id && (int)$id > 0 && $group && (int)$group > 0 && (int)$group < 4)
            {
                return true;
            }
            break;
    }
    return false;
}

function is_allowed($component = '', $action = FALSE, $permission = '')
{
    if(trim(strtoupper($permission)) == 'FULL')
    {
        return true;
    }
    elseif($action != FALSE && trim($action) != '')
    {
        if(trim(strtoupper($action)) == 'DELETE')
        {
            $action = 'DELETE';
        }
        else
        {
            $action = 'UPDATE';
        }
        if($component && trim($component) != '' && $permission && trim($permission) != '' && stristr($permission, '{('.strtoupper(trim($component).'VIEW').')}') != false && stristr($permission, '{('.strtoupper(trim($component).$action).')}') != false)
        {
            return true;
        }
    }
    elseif($component && trim($component) != '' && $permission && trim($permission) != '' && stristr($permission, '{('.strtoupper(trim($component).'VIEW').')}') != false)
    {
        return true;
    }
    return false;
}

function code($length = 6, $type = 3)
{
    $numbers = '0123456789';
    $chars = 'abcdefghijklmnopqrstvuwxyz';
    switch((int)$type)
    {
        case 1:
            $str = $numbers;
            break;
        case 2:
            $str = $chars;
            break;
        case 3:
            $str = strtoupper($chars);
            break;
        case 4:
            $str = $numbers.$chars;
            break;
        case 5:
            $str = $numbers.strtoupper($chars);
            break;
        case 6:
            $str = $chars.strtoupper($chars);
            break;
        default:
            $str = $numbers.$chars.strtoupper($chars);
    }
    $code = '';
    for($i = 0; $i < $length; $i++)
    {
        $code .= substr($str, rand(0, strlen($str) - 1), 1);
    }
    return $code;
}

function do_hash($str = '', $key = '', $admin = false)
{
    if($admin == true)
    {
        $str = hash('sha512', $str);
    }
    else
    {
        $str = hash('sha256', $str);
    }
    if(trim($key) == '')
    {
        return md5(hash('sha512', substr($str, strlen($str)/2, strlen($str)/2).substr($str, 0, strlen($str)/2)));
    }
    return md5(hash('sha512', substr($str, strlen($str)/2, strlen($str)/2).md5($key).substr($str, 0, strlen($str)/2)));
}

function safe_id($ids = array())
{
    if(is_array($ids) && count($ids) > 0)
    {
        $idSafe = array();
        foreach($ids as $id)
        {
            $idSafe[] = abs((int)$id);
        }
        return $idSafe;
    }
    elseif(!is_array($ids))
    {
        return abs((int)$ids);
    }
    return '0';
}

function search($field = '', $keywords = '', $date = false)
{
    if($date == true)
    {
        $keywords = explode('-', trim(preg_replace('/[^0-9]/', '-', trim($keywords)), '-'));
        if(isset($keywords[0]) && (int)$keywords[0] > 0 && (int)$keywords[0] <= 31 && isset($keywords[1]) && (int)$keywords[1] > 0 && (int)$keywords[1] <= 12 && isset($keywords[2]) && (int)$keywords[2] > 0 && strlen((string)((int)$keywords[2])) == 4)
        {
            return "($field >= ".(int)mktime(0, 0, 0, (int)$keywords[1], (int)$keywords[0], (int)$keywords[2])." AND $field <= ".(int)mktime(23, 59, 59, (int)$keywords[1], (int)$keywords[0], (int)$keywords[2]).")";
        }
    }
    elseif(trim($keywords) != '')
    {
        $keywords = explode(' ', $keywords);
        $sql = array();
        foreach($keywords as $keyword)
        {
            if(trim($keyword) != '')
            {
                $sql[] = "$field LIKE '%$keyword%'";
            }
        }
        return "(".implode(" OR ", $sql).")";   
    }
    return "(0 = 1)";
}

function sub($str = '', $length = 0, $ep = true)
{
    $max = 1000000000;
    if($length >= strlen($str))
    {
        return $str;
    }
    $sp = strpos($str, ' ', $length);
    $tp = strpos($str, '\t', $length);
    $np = strpos($str, '\n', $length);
    if($sp === false)
    {
        $sp = $max;
    }
    if($tp === false)
    {
        $tp = $max;
    }
    if($np === false)
    {
        $np = $max;
    }
    $length = min($sp, $tp, $np);
    if($length >= strlen($str))
    {
        return $str;
    }
    return substr($str, 0, $length).($ep?' ...':'');
}

function url($str = '')
{
    $vMap = array(
					'ế' => 'e',
					'ề' => 'e',
					'ể' => 'e',
					'ễ' => 'e',
					'ệ' => 'e',
					#---------------------------------E^
					'Ế' => 'e',
					'Ề' => 'e',
					'Ể' => 'e',
					'Ễ' => 'e',
					'Ệ' => 'e',
					#---------------------------------e
					'é' => 'e',
					'è' => 'e',
					'ẻ' => 'e',
					'ẽ' => 'e',
					'ẹ' => 'e',
					'ê' => 'e',
					#---------------------------------E
					'É' => 'e',
					'È' => 'e',
					'Ẻ' => 'e',
					'Ẽ' => 'e',
					'Ẹ' => 'e',
					'Ê' => 'e',
					#---------------------------------i
					'í' => 'i',
					'ì' => 'i',
					'ỉ' => 'i',
					'ĩ' => 'i',
					'ị' => 'i',
					#---------------------------------I
					'Í' => 'i',
					'Ì' => 'i',
					'Ỉ' => 'i',
					'Ĩ' => 'i',
					'Ị' => 'i',
					#---------------------------------o^
					'ố' => 'o',
					'ồ' => 'o',
					'ổ' => 'o',
					'ỗ' => 'o',
					'ộ' => 'o',
					#---------------------------------O^
					'Ố' => 'o',
					'Ồ' => 'o',
					'Ổ' => 'o',
					'Ô' => 'o',
					'Ộ' => 'o',
					#---------------------------------o*
					'ớ' => 'o',
					'ờ' => 'o',
					'ở' => 'o',
					'ỡ' => 'o',
					'ợ' => 'o',
					#---------------------------------O*
					'Ớ' => 'o',
					'Ờ' => 'o',
					'Ở' => 'o',
					'Ỡ' => 'o',
					'Ợ' => 'o',
					#---------------------------------u*
					'ứ' => 'u',
					'ừ' => 'u',
					'ử' => 'u',
					'ữ' => 'u',
					'ự' => 'u',
					#---------------------------------U*
					'Ứ' => 'u',
					'Ừ' => 'u',
					'Ử' => 'u',
					'Ữ' => 'u',
					'Ự' => 'u',
					#---------------------------------y
					'ý' => 'y',
					'ỳ' => 'y',
					'ỷ' => 'y',
					'ỹ' => 'y',
					'ỵ' => 'y',
					#---------------------------------Y
					'Ý' => 'y',
					'Ỳ' => 'y',
					'Ỷ' => 'y',
					'Ỹ' => 'y',
					'Ỵ' => 'y',
					#---------------------------------DD
					'Đ' => 'd',
					'đ' => 'd',
					#---------------------------------o
					'ó' => 'o',
					'ò' => 'o',
					'ỏ' => 'o',
					'õ' => 'o',
					'ọ' => 'o',
					'ô' => 'o',
					'ơ' => 'o',
					#---------------------------------O
					'Ó' => 'o',
					'Ò' => 'o',
					'Ỏ' => 'o',
					'Õ' => 'o',
					'Ọ' => 'o',
					'Ô' => 'o',
					'Ơ' => 'o',
					#---------------------------------u
					'ú' => 'u',
					'ù' => 'u',
					'ủ' => 'u',
					'ũ' => 'u',
					'ụ' => 'u',
					'ư' => 'u',
					#---------------------------------U
					'Ú' => 'u',
					'Ù' => 'u',
					'Ủ' => 'u',
					'Ũ' => 'u',
					'Ụ' => 'u',
					'Ư' => 'u',
					
					#---------------------------------a^
					'ấ' => 'a',
					'ầ' => 'a',
					'ẩ' => 'a',
					'ẫ' => 'a',
					'ậ' => 'a',
					#---------------------------------A^
					'Ấ' => 'a',
					'Ầ' => 'a',
					'Ẩ' => 'a',
					'Ẫ' => 'a',
					'Ậ' => 'a',
					#---------------------------------a(
					'ắ' => 'a',
					'ằ' => 'a',
					'ẳ' => 'a',
					'ẵ' => 'a',
					'ặ' => 'a',
					#---------------------------------A(
					'Ắ' => 'a',
					'Ằ' => 'a',
					'Ẳ' => 'a',
					'Ẵ' => 'a',
					'Ặ' => 'a',
					#---------------------------------A
					'Á' => 'a',
					'À' => 'a',
					'Ả' => 'a',
					'Ã' => 'a',
					'Ạ' => 'a',
					'Â' => 'a',
					'Ă' => 'a',
					#---------------------------------a
					'ả' => 'a',
					'ã' => 'a',
					'ạ' => 'a',
					'â' => 'a',
					'ă' => 'a',
					'à' => 'a',
					'á' => 'a'
				);
    return strtolower(preg_replace('/[^0-9a-zA-Z\_\-]/', '', strtr(strtr($str, $vMap), array(' '=>'-'))));
}

function yahoo_status($nick = '')
{
    $api = @file("http://opi.yahoo.com/online?u=$nick&m=t");
    if(strpos($api[0], 'NOT ONLINE') != 0)
    {
        return false;
    }
    return true;
}

function currency($currency = 0, $separ = '.')
{
    return number_format($currency, 0, '', $separ);
}

function exchange($currency = 0, $unit = 'VND')
{
    if(trim(strtoupper($unit)) == 'VND')
    {
        return currency(round($currency/EXCHANGE)).' USD';
    }
    return currency(round($currency*EXCHANGE)).' VND';
}

function date_convert($date = '', $format = true, $full = true, $time = 0)
{
    if($format == true)
    {
        if($full == true)
        {
            return date('H:i d-m-Y', (int)$date);
        }
        return date('d-m-Y', (int)$date);
    }
    $date = explode('-', $date);
    if(isset($date[0]) && isset($date[1]) && isset($date[2]))
    {
        switch((int)$time)
        {
            case 1:
                return (int)mktime(0, 0, 0, (int)$date[1], (int)$date[0], (int)$date[2]);
            case 2:
                return (int)mktime(23, 59, 59, (int)$date[1], (int)$date[0], (int)$date[2]);
            default:
                return (int)mktime(date('H'), date('i'), date('s'), (int)$date[1], (int)$date[0], (int)$date[2]);
        }
    }
    return 0;
}

function comment($str = '')
{
    if(trim($str) != '')
    {
        if(stripos($str, '[QUOTE]') !== false && stripos($str, '[/QUOTE]') !== false)
        {
            $quote = mb_substr($str, (int)stripos($str, '[QUOTE]') + 7, (int)stripos($str, '[/QUOTE]') - ((int)stripos($str, '[QUOTE]') + 7));
            $detail = mb_substr($str, (int)stripos($str, '[/QUOTE]') + 8, mb_strlen($str) - ((int)stripos($str, '[/QUOTE]') + 8));
            return array('quote'=>$quote, 'detail'=>$detail);
        }
        return array('quote'=>'', 'detail'=>$str);
    }
    return array('quote'=>'', 'detail'=>'');
}

function load_file($folder = './', $rejects = array())
{
    $listFiles = array();
    foreach(glob($folder.'*') as $item)
    {
        if(is_file($item))
        {
            $exist = false;
            foreach($rejects as $reject)
            {
                if($reject == basename($item))
                {
                    $exist = true;
                    break;
                }
            }
            if($exist == false)
            {
                $listFiles[] = basename($item);
            }
        }
    }
    return $listFiles;
}

function load_folder($folder = './', $rejects = array())
{
    $listFolders = array();
    foreach(glob($folder.'*') as $item)
    {
        if(is_dir($item))
        {
            $exist = false;
            foreach($rejects as $reject)
            {
                if($reject == basename($item))
                {
                    $exist = true;
                    break;
                }
            }
            if($exist == false)
            {
                $listFolders[] = basename($item);
            }
        }
    }
    return $listFolders;
}

function create_dir($path = '')
{
    if(trim($path) != '' && !is_dir($path))
    {
        @mkdir($path);
        if($fp = @fopen($path.'index.html', FOPEN_WRITE_CREATE_DESTRUCTIVE))
        {
            flock($fp, LOCK_EX);
            fwrite($fp, '<p>Directory access is forbidden.</p>');
            flock($fp, LOCK_UN);
            fclose($fp);
        }
    }
}

function remove_file($file = '')
{
    if(is_file($file))
    {
        @unlink($file);
    }
}

function remove_dir($path = '')
{
    if(trim($path) != '' && is_dir($path))
    {
        if(count(load_file($path, array('index.html'))) == 0)
        {
            remove_file($path.'index.html');
            @rmdir($path);
        }
    }
}

function create_thumbnail($filename = '', $path = '', $width = 100, $height = 100, $color = false, $fix = true)
{
    if(is_file($path.$filename) && trim($path) != '' && is_dir($path) && is_writable($path))
    {
        $info = @getimagesize($path.$filename);
        switch((int)$info[2])
        {
            case 1:
                $image = @imagecreatefromgif($path.$filename);
                break;
            case 2:
                $image = @imagecreatefromjpeg($path.$filename);
                break;
            default:
                $image = @imagecreatefrompng($path.$filename);
        }
        if($image)
        {
            $w = $width;
            $h = $height;
            $oldWidth = @imagesx($image);
            $oldHeight = @imagesy($image);
            $ratio = $oldWidth/$oldHeight;
            $newWidth = min($oldWidth, $width);
            $newHeight = $newWidth/$ratio;
            $newHeight = min($newHeight, $height);
            $newWidth = $newHeight*$ratio;
            if($fix == false)
            {
                $width = $newWidth;
                $height = $newHeight;
            }
            $bg = @imagecreatetruecolor($width, $height);
            if($color == false)
            {
                $color = @imagecolorallocate($bg, 255, 255, 255);
            }
            else
            {
                $color = @imagecolorallocate($bg, 238, 248, 248);
            }
            @imagefilledrectangle($bg, 0, 0, $width, $height, $color);
            @imagecopyresized($bg, $image, ($width - $newWidth)/2, ($height - $newHeight)/2, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight);
            switch((int)$info[2])
            {
                case 1:
                    @imagegif($bg, $path.'thumbnail'.$w.'X'.$h.'_'.$filename);
                    break;
                case 2:
                    @imagejpeg($bg, $path.'thumbnail'.$w.'X'.$h.'_'.$filename);
                    break;
                default:
                    @imagepng($bg, $path.'thumbnail'.$w.'X'.$h.'_'.$filename);
            }
            @imagedestroy($bg);
        }
    }
}

function show_thumbnail($prefix = '', $filename = '', $path = '', $default = 'templates/home/images/defaultImage.jpg')
{
    if(is_file($path.$prefix.$filename))
    {
        return $path.$prefix.$filename;
    }
    return $default;
}

function multi_thumbnail($prefix = '', $filenames = '', $path = '', $default = 'templates/home/images/defaultImage.jpg')
{
    if(trim($filenames) != '')
    {
        $filenames = explode('|', $filenames);
        $files = array();
        foreach($filenames as $filename)
        {
            $files[] = $filename;
        }
        return show_thumbnail($prefix, $files[0], $path, $default);
    }
    return $default;
}

function delete_thumbnail($prefixs = array(), $filename = '', $path = '')
{
    if(is_file($path.$filename))
    {
        remove_file($path.$filename);
        foreach($prefixs as $prefix)
        {
            remove_file($path.$prefix.$filename);
        }
        remove_dir($path);
    }
}

function tip($str = '', $image = false)
{
    if(is_array($str))
    {
        $tip = array();
        foreach($str as $label=>$value)
        {
            $tip[] = '<b>'.$label.':</b> '.htmlspecialchars($value);
        }
        return implode('<br>', $tip);
    }
    elseif($image == false)
    {
        return htmlspecialchars($str);
    }
    return '<img src=\''.$str.'\' />';
}